package com.xq.hibernate.sboot;

import com.xq.hibernate.sboot.entity.Customer;
import com.xq.hibernate.sboot.repository.CustomerRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

/**
 * 功能说明:SpringBoot应用类.
 * <p>创建时间: 2018-10-18 17:44</p>
 *
 * @author 郭凯强
 * @version 1.0-SNAPSHOT
 */
 @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
//@Configuration //tags the class as a source of bean definitions for the application context
//@EnableAutoConfiguration //tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings
//@ComponentScan //tells Spring to look for other components, configurations, and services in the XXX package
public class Application {
    public static final String BAUER = "Bauer";
    private final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

    /**
     * Application fetches the CustomerRepository from the Spring application context.
     * @param repository 客户Repository对象
     * @return 命令行对象
     */
    public CommandLineRunner demo(CustomerRepository repository) {
        logger.info("注入CustomerRepository 并 执行指定方法");
        return (args -> {
            // save a couple of customers
            repository.save(new Customer("Jack", BAUER));
            repository.save(new Customer("Chloe", "O'Brian"));
            repository.save(new Customer("Kim", BAUER));
            repository.save(new Customer("David", "Palmer"));
            repository.save(new Customer("Michelle", "Dessler"));

            // fetch all customers
            logger.info("Customers found with findAll();");
            logger.info("--------------------------------");
            repository.findAll().forEach(customer -> logger.info(customer.toString()));
            logger.info("");

            // fetch an individual customer by ID
            repository.findById(1L)
                    // gkq:Optional的使用
                    .ifPresent(customer -> {
                        logger.info("Customer found with findById(1L):");
                        logger.info("----------------------------------");
                        logger.info(customer.toString());
                        logger.info("");
                    });

            // fetch customers by last name
            logger.info("Customer found with findByLast('Bauer'):");
            logger.info("----------------------------------------");
            repository.findByLastName(BAUER).forEach(customer -> logger.info(customer.toString()));
            logger.info("");
        });
    }
}
